package jeye.servlet.action;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jeye.dao.EventDAO;
import jeye.dao.model.EventFrame;
import jeye.utils.ImageUtils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

public class SequenceAction implements ServletAction {
	
	private static final String ENDLN = "\r\n";

	private static final String EVENT_ID = "eventId";
	
	private static final String HEIGHT_PARAM = "height";

	private static final String WIDTH_PARAM = "width";

	private static final String QUALITY_PARAM = "quality";
	
	@Autowired
	private EventDAO eventDAO;

	public void processAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String eventIdStr = request.getParameter(EVENT_ID);
		String widthStr = request.getParameter(WIDTH_PARAM);
		String heightStr = request.getParameter(HEIGHT_PARAM);
		String qualityStr = request.getParameter(QUALITY_PARAM);
		OutputStream stream = response.getOutputStream();
		
		if(StringUtils.isNumeric(eventIdStr)) {
			long eventId = Long.parseLong(eventIdStr);
			List<EventFrame> frames = eventDAO.getEventFrames(eventId);
			String framesCount = frames.size() + ENDLN;
			
			stream.write(framesCount.getBytes());
			stream.flush();
			
			for(EventFrame eventFrame : frames) {
				byte[] frame = eventFrame.getFrame();
				byte[] outputFrame = frame;
				
				if(StringUtils.isNumeric(widthStr) && StringUtils.isNumeric(heightStr)) {
					int width = Integer.valueOf(widthStr);
					int height = Integer.valueOf(heightStr);
					
					if(StringUtils.isNotBlank(qualityStr)) {
						float quality = Float.valueOf(qualityStr);
						outputFrame = ImageUtils.resizeImage(frame, width, height, quality);
					}
					else {
						outputFrame = ImageUtils.resizeImage(frame, width, height);
					}
				}
				
				String frameLength = outputFrame.length + ENDLN;
				
				stream.write(frameLength.getBytes());
				stream.write(outputFrame);
				
				stream.flush();
			}
		}
	}

}
